package com.alinesno.cloud.operation.cmdb.controller.manager;

import java.io.File;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.builder.ReflectionToStringBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.alinesno.cloud.operation.cmdb.advice.ConvertCode;
import com.alinesno.cloud.operation.cmdb.common.constants.HasStatusEnum;
import com.alinesno.cloud.operation.cmdb.controller.BaseController;
import com.alinesno.cloud.operation.cmdb.entity.ResourceHeadthEntity;
import com.alinesno.cloud.operation.cmdb.repository.ResourceHeadthRepository;
import com.alinesno.cloud.operation.cmdb.third.data.QiniuUploadTool;
import com.alinesno.cloud.operation.cmdb.web.bean.FileMeta;
import com.alinesno.cloud.operation.cmdb.web.bean.JqDatatablesPageBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResponseBean;
import com.alinesno.cloud.operation.cmdb.web.bean.ResultGenerator;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;

/**
 * 后台主面板
 * @author LuoAnDong
 * @since 2018年8月14日 下午12:58:05
 */
@Controller
@RequestMapping("/manager/")
public class ResourceHeadthController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass()) ; 
	
	@Autowired
	private ResourceHeadthRepository resourceHeadthRepository ; 
	
	@Autowired
	private QiniuUploadTool qiniuUploadTool ; 
	
	@GetMapping("/headth_list")
	public String list(Model model) {
		
		createMenus(model); 
		return WX_MANAGER+"headth_list";
	}
	
	@GetMapping("/headth_add")
	public String accountAdd(Model model) {
		return WX_MANAGER+"headth_add";
	}

	@GetMapping("/headth_import_data")
	public String importData(Model model) {
		return WX_MANAGER + "headth_import_data";
	}
	
    @RequestMapping(value="/headth_upload_data", method = RequestMethod.POST)
    public @ResponseBody LinkedList<FileMeta> upload(MultipartHttpServletRequest request, HttpServletResponse response) {
    	
    	LinkedList<FileMeta> files =  qiniuUploadTool.uploadLocal(request , stackFileExport);
    	FileMeta f = files.get(0) ; 
    	String filePath = f.getFilePath() ;
    	
    	logger.debug("文件保存路径:{} , 保存路径:{}" , filePath , stackFileExport);
    
    	ImportParams params = new ImportParams();
        List<ResourceHeadthEntity> result = ExcelImportUtil.importExcel(new File(filePath),ResourceHeadthEntity.class, params);
        
        for (ResourceHeadthEntity e : result) {
            logger.debug(ReflectionToStringBuilder.toString(e));
            e.setMasterCode(currentManager().getMasterCode());
            
            if(StringUtils.isNotBlank(e.getHeadthJob())) {
            	e.setLastHeadthTime(new Date());
            	resourceHeadthRepository.save(e) ; 
            }
        }
        
    	return files ; 
    }
    
	@GetMapping("/headth_modify/{id}")
	public String accountModify(Model model , @PathVariable("id") String id) {
		logger.debug("id = {}" , id);
		ResourceHeadthEntity bean = resourceHeadthRepository.findById(id).get() ; 
		
		model.addAttribute("bean" , bean) ; 
		return WX_MANAGER+"headth_modify";
	}
	
	/**
	 * 数据列表
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@ConvertCode
	@ResponseBody
	@GetMapping("/headth_list_data")
	public Object accountListData(Model model , JqDatatablesPageBean page) {

		JqDatatablesPageBean p = this.toPage(model, 
				page.buildFilter(ResourceHeadthEntity.class , request)  , 
				resourceHeadthRepository, page); 
		
		return p ; 
	}

	/**
	 * 保存添加
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/headth_add_save" , method = RequestMethod.POST)
	public ResponseBean<String> saveAdd(Model model , ResourceHeadthEntity bean , String resources , HttpServletRequest request) {

		logger.debug("bean:{}", ReflectionToStringBuilder.toString(bean));
		
		bean.setMasterCode(currentManager().getMasterCode());
		bean.setLastHeadthTime(new Date());
		bean.setHasStatus(HasStatusEnum.NORMARL.getCode());
		resourceHeadthRepository.save(bean) ; 
		
		return ResultGenerator.genSuccessMessage("保存成功.") ; 
	}
	
	/**
	 * 保存权限
	 * @param model
	 * @param id
	 * @return
	 */
	@ResponseBody
	@RequestMapping(value="/headth_modify_save" , method = RequestMethod.POST)
	public ResponseBean<String> saveModify(Model model , ResourceHeadthEntity bean , HttpServletRequest request , String resources) {
		
		boolean b = false ; // accountService.modifyAccount(bean , resources , request.getRemoteHost()) ; 
		return b?ResultGenerator.genSuccessMessage("保存成功."):ResultGenerator.genFailMessage("保存失败.") ; 
	}
	 
}
